<template>
  <div>
    <div class="pheader">
      <el-carousel
        indicator-position="outside"
        :height="bodyheight"
        :autoplay="true"
        :interval="3000"
      >
        <el-carousel-item v-for="(p,index) in pptlist" :key="index">
          <h3>{{ p.title }}</h3>
          <img :src="p.image" />
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="main">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-purple-dark">
            <el-menu
              :default-active="activeIndex"
              class="el-menu-demo"
              mode="horizontal"
              @select="handleSelect"
            >
              <el-submenu index="0">
                <template slot="title">我的工作台</template>
                <el-menu-item index="2-1" @click="openfile">打开文件</el-menu-item>

                <el-menu-item index="2-2" @click="savefile">保存为文件</el-menu-item>
                <el-menu-item index="2-3" @click="daochu">导出</el-menu-item>
              </el-submenu>
              <el-menu-item index="3" @click="addpage">新建</el-menu-item>
              <el-menu-item index="4" @click="showppt">预览</el-menu-item>

              <el-submenu index="5">
                <template slot="title">音频</template>
                <el-menu-item index="5-1" @click="playaudio">播放</el-menu-item>
                <el-menu-item index="5-1" @click="stopaudio">停止</el-menu-item>
              </el-submenu>

              <el-menu-item index="7">关于我们</el-menu-item>
            </el-menu>
            <div class="line"></div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <div
            :class="['box', item.title]"
            v-contextmenu:contextmenu
            @click="showdata(item)"
            class="grid-content bg-purple ppt"
            v-for="(item, index) in pptlist"
            :key="index"
          >
            {{item.title}}
            <v-contextmenu ref="contextmenu" :theme="item.title">
              <v-contextmenu-item @click="updatebg(item)">更换背景图片</v-contextmenu-item>
              <v-contextmenu-item @click="delbg(item)">删除背景图片</v-contextmenu-item>

              <v-contextmenu-item @click="delppt(item)">删除</v-contextmenu-item>
            </v-contextmenu>
          </div>
        </el-col>
        <!--
             @selection:added="selected"
              @selection:removed="selected"
              @selection:modified="selected"
              @selection:rotating="selected"
              @selection:scaling="selected"
              @selection:moving="selected"
        -->
        <el-col :span="16">
          <div id="bodybox" @drop="drop">
            <vue-fabric
              @selection:created="selected"
              @object:moving="moving"
              ref="canvas"
              :width="width"
              :height="height"
            ></vue-fabric>
          </div>
        </el-col>

        <el-col :span="5">
          <p>
            <b>工具栏</b>
          </p>
          <div class="grid-content bg-purple">
            <el-collapse v-model="activeName" accordion>
              <el-collapse-item title="文字" name="0">
                <div class="shape">
                  <ul>
                    <li>
                      <img
                        src="./assets/images/fonts.png"
                        @dragstart="dragstart"
                        draggable="true"
                        @drag="draging"
                        @dragend="dragend"
                        data-id="fonts"
                      />
                    </li>
                  </ul>
                </div>
              </el-collapse-item>
              <el-collapse-item title="形状" name="1">
                <div class="shape">
                  <ul>
                    <li>
                      <img
                        src="./assets/images/rectangle.png"
                        data-id="rectangle"
                        @dragstart="dragstart"
                        draggable="true"
                        @drag="draging"
                        @dragend="dragend"
                      />
                    </li>
                    <li>
                      <img
                        src="./assets/images/triangle.png"
                        data-id="triangle"
                        @dragstart="dragstart"
                        draggable="true"
                        @drag="draging"
                        @dragend="dragend"
                      />
                    </li>
                    <li>
                      <img
                        src="./assets/images/circle.png"
                        data-id="circle"
                        @dragstart="dragstart"
                        draggable="true"
                        @drag="draging"
                        @dragend="dragend"
                      />
                    </li>
                  </ul>
                </div>
              </el-collapse-item>
              <el-collapse-item title="线条" name="2">
                <div class="shape">
                  <ul>
                    <li>
                      <img
                        src="./assets/images/solid_line.png"
                        data-id="solid_line"
                        @dragstart="dragstart"
                        draggable="true"
                        @drag="draging"
                        @dragend="dragend"
                      />
                    </li>
                    <li>
                      <img
                        src="./assets/images/dotted_line.png"
                        data-id="dotted_line"
                        @dragstart="dragstart"
                        draggable="true"
                        @drag="draging"
                        @dragend="dragend"
                      />
                    </li>
                    <!-- <li>
                    <img
                      src="./assets/images/curve.png"
                      data-id="curve"
                      @dragstart="dragstart"
                      draggable="true"
                      @drag="draging"
                      @dragend="dragend"
                    />
                    </li>-->
                    <li>
                      <img
                        src="./assets/images/arrow.png"
                        data-id="arrow"
                        @dragstart="dragstart"
                        draggable="true"
                        @drag="draging"
                        @dragend="dragend"
                      />
                    </li>
                  </ul>
                </div>
              </el-collapse-item>
              <el-collapse-item title="图片" name="3">
                <div class="shape">
                  <ul>
                    <li>
                      <el-upload
                        class="avatar-uploader"
                        action
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                      >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                    </li>
                    <li v-for="img in imglist" :key="img">
                      <img
                        style="width:100%"
                        :src="img"
                        data-id="image"
                        @dragstart="dragstartimg"
                        draggable="true"
                        @drag="draging"
                        @dragend="dragend"
                      />
                    </li>
                  </ul>
                </div>
              </el-collapse-item>
              <el-collapse-item title="音视频" name="4">
                <div class="shape">
                  <ul>
                    <li>
                      <img
                        src="./assets/images/audio.png"
                        id="audio"
                        data-id="audio"
                        @click="uploadaudio"
                      />
                    </li>

                    <!-- <li style="margin-left:10px;">
                      <img src="./assets/images/video.png" data-id="video" @click="uploadvideo" />
                    </li>-->
                  </ul>
                </div>
              </el-collapse-item>
              <el-collapse-item title="功能图" name="5">
                <div>用户决策：根据场景可给予用户操作建议或安全提示，但不能代替用户进行决策；</div>
                <div>结果可控：用户可以自由的进行操作，包括撤销、回退和终止当前操作等。</div>
              </el-collapse-item>
              <el-collapse-item title="表格" name="6">
                <div>用户决策：根据场景可给予用户操作建议或安全提示，但不能代替用户进行决策；</div>
                <div>结果可控：用户可以自由的进行操作，包括撤销、回退和终止当前操作等。</div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-col>
      </el-row>
    </div>

    <input type="file" id="fileEle" name="myfile" style="display:none" />
  </div>
</template>

<script>
import Home from "./components/Home.vue";
import canvasutil from "./assets/js/canvas";
import uuidv1 from "uuid/v1";
import myutil from "./assets/js/myutil";

Array.prototype.remove = function(val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};
export default {
  name: "app",
  data() {
    return {
      imagelist: [],
      pptlist: [{ title: "空白演示", data: "", id: 0, image: "", audio: "" }],
      activeIndex: "1",
      width: 800,
      height: 600,
      bodyheight: 500,
      activeName: "0",
      options: {
        id: "test"
      },
      imageUrl: "",
      imglist: [],
      imgtemp: "",
      pageindex: 0,
      mycanvas: {},
      pptisshow: false
    };
  },
  components: {
    Home
  },
  mounted: function() {
    var that = this;
    $(document).keydown(function(event) {
      console.log("event.keyCode ", event.keyCode);
      if (event.keyCode == 46) {
        that.$refs.canvas.removeCurrentObj();
      } else if (event.keyCode == 119) {
        that.showppt();
      } else if (event.keyCode == 27) {
        that.hideppt();
      }
    });
    if (this.pptisshow == false) {
      this.canvasinit();
    }
  },
  methods: {
    addpage() {
      this.pageindex = this.pageindex + 1;
      this.pptlist.push({
        title: "空白演示",
        data: "",
        image: "",
        id: this.pageindex,
        audio: ""
      });
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    canvasinit() {
      console.log("ok");

      canvasutil.canvas = this.$refs.canvas;
      canvasutil.clear();

      // var c = document.getElementsByClassName("upper-canvas")[0];
      // var ctx = c.getContext("2d");
      // ctx.rect(20, 20, 150, 100);
      // ctx.stroke();

      var that = this;
      $(".upper-canvas").mouseup(function() {
        console.log("111", new Date());
        that.savedata();
      });
      //#d3dce6
    },
    dragstart(ev) {
      ev.dataTransfer.setData("temp", ev.target.dataset.id);

      this.offsetX = ev.offsetX;
      this.offsetY = ev.offsetY;
    },
    dragstartimg(ev) {
      // console.log("sss",ev.target.src);
      ev.dataTransfer.setData("temp", ev.target.dataset.id);
      this.imgtemp = ev.target.src;
      this.offsetX = ev.offsetX;
      this.offsetY = ev.offsetY;
    },
    draging(e) {
      // console.log('拖动中')
      var x = e.clientX;
      var y = e.clientY;
      // console.log('shubiao client')
      if (x > 300) {
        console.log(this.tags);
        // drag事件最后一刻，无法读取鼠标的坐标，pageX和pageY都变为0
        if (x === 0 && y === 0) {
          return; // 不处理拖动最后一刻X和Y都为0的情形
        }
        x -= this.offsetX;
        y -= this.offsetY;
        // console.log('e left')
        // console.log(x + '-' + y)
        /* 它的父级第一个存在定位的元素，如果有margin减去margin值  */
        e.target.style.left = x - 5 + "px";
        e.target.style.top = y - 60 + "px";
      }
    },
    drop(ev) {
      console.log("drop拖放事件,绑定可拖放区域", event);
      var temp = ev.dataTransfer.getData("temp");
      this.painting(temp, event);
    },
    dragend(event) {
      this.savedata();
      event.dataTransfer.clearData();
    },
    painting(key, ev) {
      console.log("key", key);
      console.log("ev.offsetX", ev.offsetX);
      console.log("ev.offsetY", ev.offsetY);
      switch (key) {
        case "fonts":
          var options = {
            id: uuidv1(),
            top: ev.offsetY,
            left: ev.offsetX,
            width: 50
          };
          canvasutil.createTextbox("这是一段文字", options);

          break;
        case "rectangle":
          var options = {
            id: uuidv1(),
            top: ev.offsetY,
            left: ev.offsetX,
            fills: "white",
            stroke: "black",
            width: 200,
            height: 100
          };
          canvasutil.createRect(options);

          break;
        case "triangle":
          var options = {
            id: uuidv1(),
            top: ev.offsetY,
            left: ev.offsetX,
            fills: "white",
            stroke: "black",
            width: 200,
            height: 100
          };
          canvasutil.createEqualTriangle(options);

          break;
        case "circle":
          var options = {
            id: uuidv1(),
            top: ev.offsetY,
            left: ev.offsetX,
            fills: "white",
            stroke: "black",
            radius: 100
          };

          canvasutil.createCircle(options);

          break;
        case "image":
          var options = {
            id: uuidv1(),
            top: ev.offsetY,
            left: ev.offsetX,
            registeObjectEvent: true
          };
          canvasutil.createImage(this.imgtemp, options);

          break;
        case "solid_line":
          var options = {
            id: uuidv1(),
            top: ev.offsetY,
            left: ev.offsetX,
            x: 100,
            y: 100,
            x1: 200,
            y1: 200,
            strokeColor: "#000000"
          };

          canvasutil.createLine(options);

          break;
        case "dotted_line":
          var options = {
            id: uuidv1(),
            top: ev.offsetY,
            left: ev.offsetX,
            x: 100,
            y: 100,
            x1: 200,
            y1: 200,
            drawWidth: 1,
            strokeColor: "#000000"
          };

          canvasutil.drawDottedline(options);

          break;
        case "arrow":
          var options = {
            id: uuidv1(),
            top: ev.offsetY,
            left: ev.offsetX,
            x: 100,
            y: 100,
            x1: 200,
            y1: 200,
            strokeColor: "#000000",
            theta: 30,
            headlen: 30
          };

          canvasutil.drawArrowLine(options);

          break;
      }
    },
    savedata() {
      console.log("this.pageindex", this.pageindex);
      this.pptlist[this.pageindex].data = canvasutil.canvas.toJson();
      this.pptlist[this.pageindex].image = canvasutil.canvas.toDataUrl();
    },

    handleAvatarSuccess(res, file) {
      // var img = URL.createObjectURL(file.raw);
      // this.imglist.push(img);
    },
    beforeAvatarUpload(file) {
      var that = this;
      const isJPG = file.type === "image/jpg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      console.log("file", file);
      var reader = new FileReader();
      reader.readAsDataURL(file); //读取图像文件 result 为 DataURL, DataURL 可直接 赋值给 img.src
      reader.onload = function(event) {
        that.imglist.push(event.target.result);
      };

      return isJPG && isLt2M;
    },
    selected(event) {
      console.log("ss", event);
      var selected = event.selected;
    },
    mouseup(event) {
      console.log("cc");
    },
    delppt(uitem) {
      console.log("uitem", uitem);
      if (this.pptlist.length > 1) {
        this.pptlist.remove(uitem);
      } else {
        const h = this.$createElement;
        this.$notify({
          title: "系统提示",
          message: h("i", { style: "color: teal" }, "只剩下一个了不能删除哦")
        });
      }
    },
    showdata(uitem) {
      console.log("uitem.id;", uitem.id);
      this.pageindex = uitem.id;
      canvasutil.clear();

      canvasutil.loadFromJSON(uitem.data);
    },
    updatebg(uitem) {
      var _this = this;
      const h = this.$createElement;
      var fileEle = $("#fileEle");
      fileEle.click();
      $("#fileEle").change(function() {
        var reads = new FileReader();
        var f = $(this).get(0).files[0];
        var rep = /jpeg|png|gif|bmp/gi;
        var gstyle = f.type.split("/")[1];
        if (rep.test(gstyle)) {
          reads.readAsDataURL(f);
          var that = this;
          reads.onload = function(e) {
            // console.log("e.target.result", e.target.result);
            var obj = {
              key: "bg",
              image: e.target.result,
              id: uuidv1()
            };
            canvasutil.setBackgroundImage(e.target.result);
          };
        } else {
          _this.$notify({
            title: "系统提示",
            message: h(
              "i",
              { style: "color: teal" },
              "图片格式不正确，请上传 jpeg|png|gif|bmp 格式的图片"
            )
          });
        }
      });
    },
    delbg(uitem) {
      // var data = this.pptlist[this.pageindex].data;
      // var id = "";
      // for (var i = 0; i < data.length; i++) {
      //   if (data[i].key == "bg") {
      //     id = data[i].id;
      //     break;
      //   }
      // }
      // if (id != "") {
      //   canvasutil.removeobj({ id: id });
      // }
      var ss = canvasutil.canvas.clear();
      console.log("ss", ss);
    },
    showppt() {
      $(".pheader").show();
      $(".main").hide();
      var list = this.pptlist;
      var audio;
      for (var i = 0; i < list.length; i++) {
        if (list[i].audio != "") {
          audio = list[i].audio;
        }
      }
      myutil.play(audio);
      this.pptisshow = true;
    },
    hideppt() {
      $(".pheader").hide();
      $(".main").show();
      this.pptisshow = false;
      myutil.stop();
    },
    openfile() {
      var _this = this;
      const h = this.$createElement;
      var fileEle = $("#fileEle");
      fileEle.click();
      $("#fileEle").change(function() {
        var reads = new FileReader();
        var f = $(this).get(0).files[0];

        var gstype = f.name.split(".")[1];
        console.log("gstyle", gstype);
        if (gstype == "ppty") {
          reads.readAsText(f);
          var that = this;
          reads.onload = function(e) {
            console.log("e.target.result", e.target.result);
            var ss = e.target.result;

            _this.pageindex = 0;
            _this.pptlist = JSON.parse(ss);
            _this.showdata({ id: 0, data: _this.pptlist[0].data });

            // var json = JSON.parse(e.target.result);
            // console.log("json",json);
          };
        } else {
          _this.$notify({
            title: "系统提示",
            message: h("i", { style: "color: teal" }, "文件格式不正确")
          });
        }
      });
    },
    savefile() {
      try {
        var str = JSON.stringify(this.pptlist);

        // var buf = new ArrayBuffer(str.length * 2);
        // var bufView = new Uint16Array(buf);
        // for (var i = 0, strLen = str.length; i < strLen; i++) {
        //   bufView[i] = str.charCodeAt(i);
        // }

        var blob = new Blob([str], { type: "text/plain" });

        saveAs(blob, "文档.ppty");
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, blob);
      }
    },
    daochu() {},
    moving() {
      console.log("moving");
    },
    uploadaudio() {
      var _this = this;
      const h = this.$createElement;
      var fileEle = $("#fileEle");
      fileEle.click();
      $("#fileEle").change(function() {
        var reads = new FileReader();
        var f = $(this).get(0).files[0];

        var gstype = f.name.split(".")[1];
        console.log("gstyle", gstype);
        if (gstype == "mp3") {
          reads.readAsArrayBuffer(f);
          var that = this;
          reads.onload = function(e) {
            var blob = new Blob([e.target.result]);
            console.log("typeof", typeof blob);
            _this.pptlist[_this.pageindex].audio = blob;
            console.log("  _this.pptlist", _this.pptlist);

            var options = {
              id: uuidv1(),
              top: 100,
              left: 100,
              registeObjectEvent: true
            };
            var image = $("#audio").attr("src");
            canvasutil.createImage(image, options);
          };
        } else {
          _this.$notify({
            title: "系统提示",
            message: h("i", { style: "color: teal" }, "文件格式不正确")
          });
        }
      });
    },
    uploadvideo() {},
    playaudio() {
      const h = this.$createElement;
      var _this = this;
      console.log("_this.pptlist", _this.pptlist);
      var audio = _this.pptlist[_this.pageindex].audio;

      if (audio == "") {
        _this.$notify({
          title: "系统提示",
          message: h("i", { style: "color: teal" }, "当前页面没有音频文件")
        });
      } else {
        console.log("result", typeof audio);
        myutil.play(audio);
      }
    },
    stopaudio() {
      var obj = this.pptlist[this.pageindex];
      myutil.stop(obj);
    }
  },
  created() {
    var width = document.body.offsetWidth;
    var height = window.screen.availHeight;
    console.log("heigth", height);

    this.bodyheight = height - 180 + "px";
    console.log("wdith", width);
    var w = (width / 24) * 16;
    this.width = w - 20;
  }
};
</script>

<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.ppt {
  height: 150px;
  text-align: center;
  vertical-align: middle;
  line-height: 150px;
  margin-top: 10px;
}
.shape ul {
  padding: 0px;
  margin: 0px;
  min-height: 100px;
}
.shape ul li {
  list-style: none;
  width: 80px;
  height: 80px;
  float: left;
  margin: 10px;
}
.shape ul li img {
  width: 80px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
.el-upload {
  height: 70px;
  line-height: 80px !important;
}
.v-contextmenu {
  background-color: #d3dce6 !important;
}
.el-carousel__item {
  text-align: center;
}
.pheader {
  display: none;
}
</style>
